// SVG资源管理器
export class SVGAssetManager {
    private loadedSVGs: Map<string, string> = new Map();
    private loadPromises: Map<string, Promise<string>> = new Map();
    
    // SVG文件路径映射
    private assetPaths: Record<string, string> = {
        // 伊朗导弹
        'FATEH_110': '/svg/weapons/iranian/fateh-110.svg',
        'SHAHAB_3': '/svg/weapons/iranian/shahab-3.svg',
        'FATTAH_2': '/svg/weapons/iranian/fattah-2.svg',
        'SHAHED_136': '/svg/weapons/iranian/shahed-136.svg',
        'QIAM_1': '/svg/weapons/iranian/qiam-1.svg',
        'ZELZAL_2': '/svg/weapons/iranian/zelzal-2.svg',
        
        // 以色列防御系统
        'IRON_DOME': '/svg/weapons/israeli/iron-dome.svg',
        'ARROW_3': '/svg/weapons/israeli/arrow-3.svg',
        'GREEN_PINE_RADAR': '/svg/weapons/israeli/green-pine-radar.svg',
        
        // 背景和地形
        'GAME_BACKGROUND': '/svg/terrain/game-background.svg',
        'CITY_SKYLINE': '/svg/terrain/city-skyline.svg',
        'MEDITERRANEAN_SEA': '/svg/terrain/mediterranean-sea.svg',
        'DEFENSE_GRID': '/svg/terrain/defense-grid.svg',
        
        // 特效
        'EXPLOSION': '/svg/effects/explosion.svg',
        
        // 建筑
        'MISSILE_LAUNCH_SITE': '/svg/buildings/iranian/missile-launch-site.svg',
        'GOVERNMENT_BUILDING': '/svg/buildings/israeli/government-building.svg'
    };
    
    async loadSVG(key: string): Promise<string> {
        // 如果已经加载过，直接返回
        if (this.loadedSVGs.has(key)) {
            return this.loadedSVGs.get(key)!;
        }
        
        // 如果正在加载，返回现有的Promise
        if (this.loadPromises.has(key)) {
            return this.loadPromises.get(key)!;
        }
        
        const path = this.assetPaths[key];
        if (!path) {
            throw new Error(`SVG asset not found: ${key}`);
        }
        
        // 创建加载Promise
        const loadPromise = this.fetchSVG(path);
        this.loadPromises.set(key, loadPromise);
        
        try {
            const svgContent = await loadPromise;
            this.loadedSVGs.set(key, svgContent);
            this.loadPromises.delete(key);
            return svgContent;
        } catch (error) {
            this.loadPromises.delete(key);
            console.error(`Failed to load SVG ${key} from ${path}:`, error);
            throw error;
        }
    }
    
    private async fetchSVG(path: string): Promise<string> {
        try {
            const response = await fetch(path);
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            return await response.text();
        } catch (error) {
            console.error(`Failed to fetch SVG from ${path}:`, error);
            // 返回备用SVG或抛出错误
            return this.getFallbackSVG();
        }
    }
    
    private getFallbackSVG(): string {
        // 简单的备用SVG
        return `<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
            <rect width="20" height="20" fill="red" opacity="0.8"/>
            <text x="10" y="15" text-anchor="middle" fill="white" font-size="12">?</text>
        </svg>`;
    }
    
    // 批量预加载资源
    async preloadAssets(keys: string[]): Promise<void> {
        console.log(`🎨 开始预加载 ${keys.length} 个SVG资源...`);
        
        const loadPromises = keys.map(key => 
            this.loadSVG(key).catch(error => {
                console.warn(`Failed to preload ${key}:`, error);
                return null;
            })
        );
        
        await Promise.all(loadPromises);
        console.log('✅ SVG资源预加载完成');
    }
    
    // 获取已加载的SVG
    getSVG(key: string): string | null {
        return this.loadedSVGs.get(key) || null;
    }
    
    // 创建SVG元素
    createSVGElement(key: string, width?: number, height?: number): SVGElement | null {
        const svgContent = this.getSVG(key);
        if (!svgContent) {
            return null;
        }
        
        const parser = new DOMParser();
        const doc = parser.parseFromString(svgContent, 'image/svg+xml');
        const svgElement = doc.documentElement as any as SVGElement;
        
        if (width !== undefined) {
            svgElement.setAttribute('width', width.toString());
        }
        if (height !== undefined) {
            svgElement.setAttribute('height', height.toString());
        }
        
        return svgElement;
    }
    
    // 获取所有可用的资源键
    getAvailableAssets(): string[] {
        return Object.keys(this.assetPaths);
    }
    
    // 清除缓存
    clearCache(): void {
        this.loadedSVGs.clear();
        this.loadPromises.clear();
        console.log('🗑️ SVG缓存已清除');
    }
}

// 全局SVG资源管理器实例
export const svgAssetManager = new SVGAssetManager();
